package jhelp;

import java.io.File;
import java.io.IOException;
import java.util.Hashtable;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XMLDataProcessor implements DataProcessor{
	public Hashtable<String, Record> dispatchDataInHashtable(String dataSourcePath) {
		Hashtable<String, Record> dataTable= new Hashtable<String, Record>();
		try {
			File xmlFile = new File(dataSourcePath);
		    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
		    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
		    Document document = documentBuilder.parse(xmlFile);
		    document.getDocumentElement().normalize();
			
			
		    document.getDocumentElement().normalize();
		    NodeList nodeList = document.getDocumentElement().getElementsByTagName("record");
		    for(int i = 0; i < nodeList.getLength(); i++){
		    	Element currentElement = (Element)(nodeList.item(i));
		    	
		    	String term = "", value = "";
		    	if(currentElement.getElementsByTagName("term").item(0).getChildNodes().item(0) != null)
		    		term = currentElement.getElementsByTagName("term").item(0).getChildNodes().item(0).getNodeValue();
		    	if(currentElement.getElementsByTagName("value").item(0).getChildNodes().item(0) != null)
		    		value = currentElement.getElementsByTagName("value").item(0).getChildNodes().item(0).getNodeValue();
		    	Record rec = new Record(Integer.parseInt(currentElement.getAttribute("id")), term, value);
		    	dataTable.put(rec.getTerm(), rec);
		    }
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		return dataTable;
	}
}